<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/dbConnection.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/avatar.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busResource.php';

class FavouriteDao {
	private $_db;

	public function __construct() {
		$this->_db = new DbConnection();
		$this->_db->connect();
	}

	public function addFavourite($favourite) {
		$query = sprintf("CALL sp_AddFavourite('%u', '%u', '%u', '%u')", 
			$favourite->getUserId(), $favourite->getInteractType(), $favourite->getIndicteeId(), $favourite->getCreatedDate());
			
		$result = $this->_db->executeQuery($query);

		if (!$result) {
		    echo 'Could not run query: ' . ' ' . mysql_error();
		    return 0;
		}
		
		$row = mysql_affected_rows();		
		
		return ($row != 0);		
	}	
	
	public function removeFavourite($favourite) {
		$query = sprintf("CALL sp_RemoveFavourite('%u', '%u', '%u')", 
			$favourite->getUserId(), $favourite->getInteractType(), $favourite->getIndicteeId());
			
		$result = $this->_db->executeQuery($query);

		if (!$result) {
		    echo 'Could not run query: ' . ' ' . mysql_error();
		    return 0;
		}
		
		$row = mysql_affected_rows();		
		
		return ($row != 0);		
	}		
	
	public function isFavourite($userID, $interactType, $indicteeID) {
		$query = sprintf("SELECT * FROM favourites WHERE UserId = '%u' AND InteractType = '%u' AND IndicteeId = '%u'", 
					$userID, $interactType, $indicteeID);
				
		$result = $this->_db->executeQuery($query);

		if (!$result) {
			echo 'Could not run query: ' . ' ' . mysql_error();
		    return;
		}
		
		if (mysql_fetch_row($result)) {
			mysql_free_result($result);
			return true;
		}
		return false;
	}
	
	public function getFavouritesOfUser($userID, $interactType) {
		$query = sprintf("SELECT * FROM favourites WHERE UserId = '%u' AND InteractType = '%u'", $userID, $interactType);
		
		$result = $this->_db->executeQuery($query);
		
		if (!$result) {
			echo 'Could not run query: ' . ' ' . mysql_error();
		    return;
		}
		
		$favList = array();
		while($row = mysql_fetch_assoc($result)) {			
			$fav = new FavouriteModel();
			$fav->setUserID($row['UserId']);
			$fav->setCreatedDate($row['CreatedDate']);
			$fav->setInteractType($row['InteractType']);
			$fav->setIndicteeID($row['IndicteeId']);
			
			$favList[] = $fav;
		}
		
		return $favList;		
	}
}
?>